<template>
  <div class="llt-table">
    <div
      class="aic jcb llt-table-right formBox"
      :class="border ? 'llt-table-header' : ''"
    >
      <div class="llt-table-left aic flex1 flexWrap">
        <slot name="tableHeader"> </slot>
      </div>
      <div class="llt-table-right aic">
        <div class="" @click="handleDrawerBool">
          <el-icon class="llt-icon-size-21 mx15"><setting /></el-icon>
        </div>
      </div>
    </div>
    <div class="tableContent">
      <div>
        <filterView
          :filterTabs="state.filters"
          @handleDeleteTag="handleDeleteTag"
          @handleCloseAll="handleCloseAll"
        >
        </filterView>
      </div>
      <slot name="tableContent">
        <el-table
          ref="tableRef"
          stripe
          height="100%"
          v-loading="state.loading"
          :data="state.tableData"
          v-bind="tableOptions"
          @selection-change="handleselectionChangeRow"
        >
          <!-- 多选 -->
          <el-table-column
            v-if="selection"
            type="selection"
            :reserve-selection="reserveSelection"
            width="40"
          />
          <template v-for="(item, index) in columnsSelf" :key="index">
            <TableColumn v-if="item.visible" :item="item" >
                   
            
           
            </TableColumn>
          </template>
          <!-- 操作 -->
          <slot name="operation">
            <TableColumn :item="operation" v-if="operation" />
          </slot>
          <!-- 插入表格最后一行之后的插槽 -->
          <template #append>
            <slot name="append"> </slot>
          </template>

          <!-- 表格无数据情况 -->
          <template #empty>
            <div class="table-empty">
              <slot name="empty">
                <el-result title="抱歉，当前暂无数据。" sub-title="">
                  <template #icon>
                    <img
                      style="width: 300px"
                      src="/icon/emptyData.svg"
                      alt=""
                    />
                  </template>
                </el-result>
              </slot>
            </div>
          </template>
        </el-table>
      </slot>
    </div>
    <div>
      <el-pagination
        v-if="pagination.total"
        class="paginationBox"
        v-model="pagination.currentPage"
        :page-size="pagination.pageSize"
        :layout="pagination.layout"
        :page-sizes="pagination.pageSizes"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
      <columnSetting
        :columns="columnsSelf"
        @handelColumns="handelColumns"
        ref="columnSettingRef"
      ></columnSetting>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onUpdated,
  nextTick,
  PropType,
  computed,
  watch,
  unref,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "./Column";

import filterView from "/@/components/Filter/filterView.vue";
import columnSetting from "/@/components/table/component/columnSetting.vue";
import { type } from "os";
import { ElMessage } from "element-plus";
import { FilterValueFormat, getFormData, resetFilter } from "./hook";

const router = useRouter();
const emit = defineEmits([
  "getCurrentColumns",
  "size-change",
  "current-change",
  "selection-change",
  "result",
]);
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  getList();
};
const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page;
  getList();
};
const route = useRoute();
onMounted(() => {});

let drawerBool = ref(false);

const props: any = defineProps({
  operation: {
    //列数据
    type: Object,
    default: null,
  },
  tableOptions: {
    //列数据
    type: Object,
    default: () => {
      return {};
    },
  },
  columns: {
    //列数据
    type: Array,
    default: [],
  },
  loading: {
    //高度是否撑满   true
    type: Boolean,
    default: true,
  },
  isInit: {
    //是否初始化数据   true
    type: Boolean,
    default: true,
  },
  dataKey: {
    //   true
    type: String,
    default: "rows",
  },

  // 是否多选
  selection: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  // 仅对 type=selection 的列有效，类型为 Boolean，为 true 则会在数据更新之后保留之前选中的数据（需指定 row-key）
  reserveSelection: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  pageInfo: {
    //列数据
    type: Object,
    default: {
      currentPage: 1,
      total: 0,
      pageSize: 40,
      pageSizes: [100, 200, 300, 400],
      layout: "total, prev, pager, next,sizes",
    },
  },
  apiFunction: {
    //列数据
    type: Function,
    default: () => {},
  },
  data: {
    type: Array,
    default: null,
  },
});

const pagination = computed(() => {
  return props.pageInfo;
});
const columnsSelf = ref<TableColumn[]>([]);
watch(
  () => props.columns,
  (val) => {
    columnsSelf.value = val;
  },
  { deep: true, immediate: true },
);
const state: any = reactive({
  tableData: [],
  filters: [], //筛选展示数据
  screenModeDataObj: {}, //筛选查询数据
  loading: true,
  formFilter: {},
});
const handleDeleteTag = (indexValue: any, index: any) => {
  state.screenModeDataObj = {};
  //删除指定标签数据 并且
  state.filters[index].value.splice(indexValue, 1);
  //获取当前操作的值
  let currentKeyData = state.filters[index];

  if (currentKeyData.value == 0) {
    //删除这个字段
    state.filters.splice(index, 1);
  }
  //同步数据  formFilter
  state.formFilter[currentKeyData.key].splice(indexValue, 1);
  // 获取列表请求参数
  if (Object.keys(FilterValueFormat(state.filters)).length == 0) {
    state.screenModeDataObj = {};
  } else {
    Object.assign(state.screenModeDataObj, FilterValueFormat(state.filters));
  }
  pagination.value.currentPage = 1;
  getList();
};
const handleCloseAll = (indexValue: any, index: any) => {
  resetFilter(state.formFilter);

  state.filters = [];
  state.screenModeDataObj = {};
  pagination.value.currentPage = 1;
  getList();
};
const handleOrder = ({ data, valueKey, title }: any) => {
  if (data) {
    state.screenModeDataObj["isAsc"] = data.order;
    state.screenModeDataObj["orderByColumn"] = valueKey;
  } else {
    state.screenModeDataObj["isAsc"] = "";
    state.screenModeDataObj["orderByColumn"] = "";
  }
  pagination.value.currentPage = 1;
  getList();
};
const handleFilterBox = ({ data, valueKey, title, type }: any) => {
  if (data.length > 0) {
    //处理数据
    state.formFilter[valueKey] = data;
    state.filters = getFormData({
      data,
      key: valueKey,
      title,
      type,
      filters: state.filters,
    });

    // 获取列表请求参数
    Object.assign(state.screenModeDataObj, FilterValueFormat(state.filters));
  } else {
    delete state.screenModeDataObj[valueKey];
    delete state.formFilter[valueKey];

    let delIndex = "";
    state.filters.forEach((item: any, index: any) => {
      if (item.key == valueKey) {
        delIndex = index;
      }
    });
    state.filters.splice(delIndex, 1);
  }
  pagination.value.currentPage = 1;

  getList();
};
/**
 * 处理复选框
 * @param selection 选中的数据
 */
const handleselectionChangeRow = (selection: any) => {
  emit("selection-change", selection);
};
/*
 * 触发列表请求
 */

const getList = (queryParams?: any) => {
  if (typeof props.apiFunction === "function") {
    const listApi = props.apiFunction;
    state.loading = true;
    const pageData = unref(pagination);
    if (queryParams && queryParams.pageNum) {
      pagination.value.currentPage = queryParams.pageNum;
    }
    listApi({
      pageNum: pageData.currentPage,
      pageSize: pageData.pageSize,
      ...state.screenModeDataObj,
      ...queryParams,
    })
      .then((result: ResponseConfig) => {
        const data: any = result;
        state.tableData = data[props.dataKey];
        pagination.value.total = result.total ? result.total : 0;
        state.loading = false;
        emit("result", result);
      })
      .catch((err: any) => {});
  } else {
    ElMessage.warning("请设置apiFunction");
  }
};
watch(
  () => props.data,
  (val) => {
    if (val) {
      state.tableData = val;
      state.loading = false;
    } else {
      if (props.isInit) {
        getList();
      }
    }
  },
  {
    deep: true,
    immediate: true,
  },
);
/**
 * 设置列表弹框
 */
const columnSettingRef = ref();
const handleDrawerBool = () => {
  columnSettingRef.value.open();
};
/**
 * 更新列表字段
 */
const tableRef = ref();
const handelColumns = (columns: TableColumn[]) => {
  columnsSelf.value = columns;

  tableRef.value.doLayout();
};
defineExpose({
  getList,
  // handleSizeChange,
  // handleCurrentChange,
  // handleDeleteTag,
  // handleCloseAll,
  handleOrder,
  handleFilterBox,
  tableRef: tableRef,
  formFilter: state.formFilter,
  // handleselectionChangeRow,
});
</script>

<style lang="scss">
.llt-table {
  height: 100%;
  display: grid;
  grid-template-rows: auto 1fr 50px;
  .tableContent {
    margin-top: 10px;
    display: grid;
    grid-template-rows: auto 1fr;
    grid-gap: 10px;
  }
  .paginationBox {
    margin-top: 10px;
  }
}
.llt-table-header {
  border-top: 1px solid #eee;
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
